const db = uniCloud.database()

const myUtils = require('my-utils')

module.exports = {
	_before: async function() { // 通用预处理器
		this.userInfo = await myUtils.getUserInfo(this)
	},
	async add(data) {
		// 判断token是否正确，能否获得uid
		if (!this.userInfo.uid) return this.userInfo;

		data.user_id = this.userInfo.uid
		data.time = Date.now()
		// 如果勾选默认，就将其他的默认改为false
		if (data.selected) {
			await db.collection('my-mall-address').where({
				user_id: this.userInfo.uid
			}).update({
				selected: false
			})
		}

		return await db.collection('my-mall-address').add(data)
	},

	async getList() {
		// 判断token是否正确，能否获得uid
		if (!this.userInfo.uid) return this.userInfo;
		return await db.collection('my-mall-address').where({
			user_id: this.userInfo.uid
		}).orderBy('selected', 'desc').orderBy('time', 'desc').get()

	},
	//修改默认地址
	async updateDefault(id) {
		if (!this.userInfo.uid) return this.userInfo;
		await db.collection('my-mall-address').where({
			user_id: this.userInfo.uid
		}).update({
			selected: false
		})

		return await db.collection('my-mall-address').doc(id).update({
			selected: true
		})
	},
	async getOne(id) {
		return await db.collection('my-mall-address').doc(id).get()
	},
	async updateOne(data) {
		// 判断token是否正确，能否获得uid
		if (!this.userInfo.uid) return this.userInfo;

		data.user_id = this.userInfo.uid
		data.time = Date.now()
		// 如果勾选默认，就将其他的默认改为false
		if (data.selected) {
			await db.collection('my-mall-address').where({
				user_id: this.userInfo.uid
			}).update({
				selected: false
			})
		}
		let newData = {
			...data
		}
		delete newData._id
		return await db.collection('my-mall-address').doc(data._id).update(newData)
	},
	// 获取默认地址
	async getDefAddress() {
		// 判断token是否正确，能否获得uid
		if (!this.userInfo.uid) return this.userInfo;

		return await db.collection('my-mall-address').where({
			user_id: this.userInfo.uid,
			selected: true
		}).get();
	}
}